<?php

namespace App\Http\Controllers\Admin\Collection;

use App\Http\Controllers\Controller;
use App\Models\Common\CollOption;
use Illuminate\Http\Request;
use Style;

//调用phpQuery类
require(app_path('Vendor/phpQuery/phpQuery.php'));


/**
 * 58同城采集类
 * Class FiveEight
 * @package App\Http\Controllers\Admin\Collection
 */
class FiveEight extends Controller{

    //简历板块----------------------------------------------------------------------------------------------------------------
    /**
     * 获取58简历信息
     * @param $listData
     * @return array
     */
    static public function getResumeInfo($listData){
        //使用phpQuery
        if(preg_match_all("/<div id=\"maincon\" class=\"maincon\">(.*)<iframe (.*)<\/iframe>/Uis", $listData, $arr)){
            if(preg_match_all("/<dl(.*)<a href=(\'|\")(.*)(\'|\")(.*)<\/a>(.*)<\/dl>/Uis", $arr[1][0], $arr1)){
                if(count($arr1[3]) > 0){
                    $arrInfo = [];
                    foreach($arr1[3] as $v){
                        if(preg_match("/(.*)jianli.58.com(.*)single\/(.*)\/\?(.*)/Uis", $v, $arr2)){
                            list($resumeUrl, $resumeUrl2) = explode('?', $v);
                            $arrInfo[] = array(
                                'resumeId' => substr($arr2[3], 0, 25),//简历ID(截取前面25个做为用户的唯一ID)
                                'resumeUrl' => trim($resumeUrl, '/') . '/'    //简历列表的跳转地址
                            );
                        }
                    }
                    //删除重复项
                    $collection = collect($arrInfo);
                    $arrInfo = $collection->unique('resumeId');
                    return $arrInfo;
                }
            };
        }else{
            //获取58简历信息匹配不存在
            return 'error';
        };
    }

    /**
     * 简历内容
     * @param $resumeId
     * @param $resumeUrl
     * @param $cookie
     * @param $collArea
     * @return array
     */
    static public function resumeCon($resumeId, $resumeUrl, $cookie, $collArea){
        //58岗位数组
        require(app_path('Repositories/Array/58_job.php'));
        require(app_path('Repositories/Array/58_language.php'));
        //$resumeUrl= 'http://jianli.58.com/resumeDetailView/single/1_Pal6Pax6OaALPEiWxa-kxIN_OaAYO9p_OJN6bEA_OTWLxEovx9p0R9e0bEoNxErNOM**/';
        $con = getCurlCon($resumeUrl, $cookie);
        if(empty($con)){
            //采集信息出错
            return 'err';
        }
        //使用phpQuery
        $con = \phpQuery::newDocument($con);
        //简历信息内容
        /**************************************************************************************************************************/
        //基本信息
        $avatar = pq(".vipResContent .headFigure")->find('img')->attr('src');//头像
        $name = pq(".vipResContent .base-info")->find('#name')->html();//姓名
        $sex = pq(".vipResContent .base-detail")->find('.sex')->html();//性别
        $birthday = pq(".vipResContent .base-detail")->find('.age')->html();
        $birthday = str_replace('岁', '', trim($birthday));//年龄
        $edu = pq(".vipResContent .base-detail")->find('.edu')->html();//学历
        $work_year = pq(".vipResContent .base-detail")->find('.stonefont')->html();//工作经验

        //匹配相似度
        preg_match("/<span>(.*)人<\/span>/Uis", pq(".vipResContent .base-detail")->html(), $arr1);
        $census = (!empty($arr1[1])) ? trim($arr1[1]) : '';//户籍
        $census = (!empty($census)) ? Common::signSimilarity($collArea, $census) : '';


        //匹配相似度
        preg_match("/<span>现居(.*)<\/span>/Uis", pq(".vipResContent .base-detail")->html(), $arr2);
        $homeaddress = (!empty($arr2[1])) ? trim($arr2[1]) : '';//居住地
        $address = $homeaddress;//地址
        $homeaddress = (!empty($homeaddress)) ? Common::signSimilarity($collArea, $homeaddress) : '';

        //工作岗位
        $expectJob = trim(pq(".vipResContent .expectInfo")->find('#expectJob')->html());//期望职位
        $intentionjobs = (!empty($expectJob)) ? $expectJob : '';//意向岗位
        $job = (!empty($expectJob)) ? explode('、', $expectJob) : [];

        //职位
        $jobsort1 = !empty($job[0]) ? Common::matchJob(trim($job[0]), $jobArray) : '';
        $jobsort2 = !empty($job[1]) ? Common::matchJob(trim($job[1]), $jobArray) : '';
        $jobsort3 = !empty($job[2]) ? Common::matchJob(trim($job[2]), $jobArray) : '';
        $jobsort4 = !empty($job[3]) ? Common::matchJob(trim($job[3]), $jobArray) : '';
        $jobsort5 = !empty($job[4]) ? Common::matchJob(trim($job[4]), $jobArray) : '';
        //工作地区
        $expectLocation = trim(pq(".vipResContent .expectInfo")->find('#expectLocation')->html());//期望地点
        $location = explode('、', $expectLocation);
        //匹配相似度
        $jobArr = Common::similarity($collArea, $location);
        $jobarea1 = !empty($jobArr[0]) ? trim($jobArr[0]) : '';
        $jobarea2 = !empty($jobArr[1]) ? trim($jobArr[1]) : '';
        $jobarea3 = !empty($jobArr[2]) ? trim($jobArr[2]) : '';
        $jobarea4 = !empty($jobArr[3]) ? trim($jobArr[3]) : '';
        $jobarea5 = !empty($jobArr[4]) ? trim($jobArr[4]) : '';

        //期望薪资
        preg_match("/<p class=\"stonefont\">(.*)期望薪资：<\/span>(.*)<\/p>/Uis", pq(".vipResContent .expectInfo"), $arr10);
        $expectedsalary = (!empty($arr10[2])) ? trim($arr10[2]) : '';//期望薪资
        $isexpectedsalary = ($expectedsalary == '面议') ? 1 : 0;
        $mobile = '';
        $email = '';

        /**************************************************************************************************************************/
        //自我评价
        $certificate = trim(pq(".vipResContent .aboutMe")->find('.edu-detail')->html());//自我评价
        $introduction = (!empty($certificate)) ? $certificate : '';
        $introduction = preg_replace('/(<br>|<br \/>)/Uis', "\r\n", $introduction);
        $basicArr = [];
        $basicArr = array(
            //  'avatar' => $avatar,
            'name' => $name,
            'sex' => $sex,
            'birthday' => $birthday,
            'education' => $edu,
            'work_year' => $work_year,
            'expectedsalary' => $expectedsalary,
            'isexpectedsalary' => $isexpectedsalary,
            'census' => $census,
            'homeaddress' => $homeaddress,
            'address' => $address,
            'jobsort1' => $jobsort1,
            'jobsort2' => $jobsort2,
            'jobsort3' => $jobsort3,
            'jobsort4' => $jobsort4,
            'jobsort5' => $jobsort5,
            'jobarea1' => $jobarea1,
            'jobarea2' => $jobarea2,
            'jobarea3' => $jobarea3,
            'jobarea4' => $jobarea4,
            'jobarea5' => $jobarea5,
            'mobile' => $mobile,
            'email' => $email,
            'introduction' => $introduction,
            'intentionjobs' => $intentionjobs,
            'show_type' => 1,
            'regtime' => date('Y-m-d H:i:s', time()),
            'updatetime' => date('Y-m-d H:i:s', time())
        );

        /**************************************************************************************************************************/
        //工作经验
        $work = pq(".vipResContent .work")->find('.experience-detail');//工作经验列表
        $workArr = [];
        if(!empty($work)){
            foreach($work as $v){
                $company = trim(pq($v)->find(".itemName")->html());//公司名称
                preg_match("/<p>工作时间：<span>(.*)(\（(.*)\）)?<\/span><\/p>/Uis", pq($v)->html(), $arr21);
                $worktime = trim($arr21[1]);
                $starttime = '';
                $endtime = '';
                if(strstr($worktime, '-')){
                    list($starttime, $endtime) = explode('-', $worktime);
                    $starttime = preg_replace('/(年|月)/', '-', $starttime) . '00';
                    $endtime = ($endtime == '至今') ? '0000-00-00' : trim(preg_replace('/(年|月)/', '-', $endtime), '-') . '-00';
                }
                //薪资水平
                preg_match("/<p>薪资水平：<span>(.*)<\/span><\/p>/Uis", pq($v)->html(), $arr22);
                $money = trim($arr22[1]);
                //在职职位
                preg_match("/<p>在职职位：<span>(.*)<\/span><\/p>/Uis", pq($v)->html(), $arr23);
                $post = trim($arr23[1]);
                $content = trim(pq($v)->find(".title-content .item-content")->html());//工作描述
                $content = preg_replace('/(<br>|<br \/>)/Uis', "\r\n", $content);
                $workArr[] = array(
                    'company' => $company,
                    'starttime' => $starttime,
                    'endtime' => $endtime,
                    'post' => $post,
                    'content' => $content,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time())
                );
            }
        }

        /**************************************************************************************************************************/
        //项目经验
        $project = pq(".vipResContent .project")->find('.experience-detail');//项目经验列表
        $projectArr = [];
        if(!empty($project)){
            foreach($project as $v){
                $project_name = trim(pq($v)->find(".itemName")->html());//项目名称
                preg_match("/<p>项目时间：<span>(.*)(\（(.*)\）)?<\/span><\/p>/Uis", pq($v)->html(), $arr31);
                $projecttime = trim($arr31[1]);
                $starttime = '';
                $endtime = '';
                if(strstr($projecttime, '-')){
                    list($starttime, $endtime) = explode('-', $projecttime);
                    $starttime = preg_replace('/(年|月)/', '-', $starttime) . '00';
                    $endtime = ($endtime == '至今') ? '0000-00-00' : trim(preg_replace('/(年|月)/', '-', $endtime), '-') . '-00';
                }
                $content = trim(pq($v)->find(".title-content .item-content:eq(0)")->html());//项目描述
                $content = preg_replace('/(<br>|<br \/>)/Uis', "\r\n", $content);
                $projectArr[] = array(
                    'project_name' => $project_name,
                    'starttime' => $starttime,
                    'endtime' => $endtime,
                    'content' => $content,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time())
                );
            }
        }

        /**************************************************************************************************************************/
        //教育经历
        $education = pq(".vipResContent .education")->find('.edu-detail');//教育经历列表
        $educationArr = [];
        if(!empty($education)){
            foreach($education as $v){
                $school = trim(pq($v)->find(".college-name")->html());//学校名称
                $graduatetime = trim(pq($v)->find(".graduate-time")->html());//毕业时间
                $graduatetime = preg_replace('/毕业/', '', $graduatetime);
                if(strstr($graduatetime, '年')){
                    $endtime = preg_replace('/(年|月)/', '-', $graduatetime) . '00';
                    $starttime = date('Y', strtotime($endtime . '-3 year')) . '-09-00';
                }else{
                    $endtime = '0000-00-00';
                    $starttime = '';
                }
                $speciality = trim(pq($v)->find(".professional")->html());//专业名称
                $educationArr[] = array(
                    'school' => $school,
                    'edu_type' => 1,
                    'starttime' => $starttime,
                    'endtime' => $endtime,
                    'speciality' => $speciality,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time())
                );
            }
        }

        /**************************************************************************************************************************/
        //语言能力
        $language = pq(".vipResContent .language")->find('.edu-detail');//语言能力列表
        $languageArr = [];
        if(!empty($language)){
            foreach($language as $v){
                preg_match_all("/<div class=\"item-content\">\s*<span class=\"language\">(.*)<span class=\"language-split\">(.*)<\/span>(.*)<span class=\"language-split\">((.*)<\/span>(.*)<\/span>).*?(.*)<\/div>/Uis", pq($v)->html(), $arr42);
                list($language, $hear) = explode('：', $arr42[1][0]);
                $language = trim($language);//语种
                //获取所有的语言
                $language = (!empty($language)) ? Common::matchOption($language, CollOption::getOption('language')) : '';
                $degree = preg_replace('/读写/', '', trim($arr42[3][0]));;//程度
                switch($degree){
                    case '入门':
                        $degree = 1;
                        break;
                    case '一般':
                        $degree = 1;
                        break;
                    case '熟练':
                        $degree = 2;
                        break;
                    case '精通':
                        $degree = 3;
                        break;
                    default:
                        $degree = 4;
                        break;
                }
                $level = trim($arr42[6][0]);//等级
                $level = (!empty($level)) ? Common::matchJob($level, $languageArray) : '';
                $languageArr[] = array(
                    'language' => $language,
                    'degree' => $degree,
                    'level' => $level,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time())
                );
            }
        }
        /**************************************************************************************************************************/
        //技能专长
        $skill = pq(".vipResContent .skillList")->find('.certificate-item');//专业技能列表
        $skillArr = [];
        if(!empty($skill)){
            foreach($skill as $v){
                $skillname = trim(pq($v)->find(".skill-name")->html());//技能名称
                $degree = trim(pq($v)->find(".skill-degree")->html());
                $degree = preg_replace('/\（(.*)\）/', '', $degree);//程度
                switch($degree){
                    case '入门':
                        $degree = 1;
                        break;
                    case '一般':
                        $degree = 1;
                        break;
                    case '熟练':
                        $degree = 2;
                        break;
                    case '精通':
                        $degree = 3;
                        break;
                    default:
                        $degree = 4;
                        break;
                }
                $skillArr[] = array(
                    'skillname' => $skillname,
                    'degree' => $degree,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time())
                );
            }
        }

        /**************************************************************************************************************************/
        //获得证书
        $certificate = pq(".vipResContent .medal")->find('.certificate-item');//获得证书列表
        $certificateArr = [];
        if(!empty($certificate)){
            foreach($certificate as $v){
                $certificate_name = trim(pq($v)->find(".certificate-name")->html());//证书名称
                $gettime = trim(pq($v)->find(".certificate-time")->html());//技能名称
                $gettime = preg_replace('/(年|月)/', '-', $gettime) . '00';
                $certificateArr[] = array(
                    'certificate_name' => $certificate_name,
                    'gettime' => $gettime,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'updatetime' => date('Y-m-d H:i:s', time())
                );
            }
        }
        /**************************************************************************************************************************/
        //其它信息
        $otherArr = [];
        //简历内容
        $arrayCon = array(
            'resumeId' => $resumeId,
            'resumeUrl' => $resumeUrl,
            'basic' => $basicArr,
            'work' => $workArr,
            'project' => $projectArr,
            'education' => $educationArr,
            'language' => $languageArr,
            'skill' => $skillArr,
            'certificate' => $certificateArr,
            'other' => $otherArr
        );
//        dd($arrayCon);
        return $arrayCon;
    }


    //企业板块----------------------------------------------------------------------------------------------------------------
    /**
     * 获取58企业信息
     * @param $listData
     * @return array|static
     */
    static public function getCompanyInfo($listData){
//        $err_msg = '333333333333333333333333333';
//        return Style::view('errors.collection', compact('err_msg'));q
//        dd(444444444);
        //使用phpQuery
        if(preg_match_all("/<div class=\"main clearfix\">(.*)<div id=\"footer\" class=\"footer\">/Uis", $listData, $arr)){
            if(preg_match_all("/<li class=\"job_item clearfix\">(.*)<div class=\"comp_name\">\s*<a href=(\'|\")(.*)(\'|\")(.*)<\/a>(.*)<\/li>/Uis", $arr[1][0], $arr1)){
                if(count($arr1[3]) > 0){
                    $arrInfo = [];
                    foreach($arr1[3] as $v){
                        if(preg_match("/(.*)qy.58.com\/(.*)\/(\?(.*))?/Uis", $v, $arr2)){
                            $arrInfo[] = array(
                                'companyId' => trim($arr2[2]),//企业ID用户的唯一ID
                                'companyUrl' => trim($v, '/') . '/'   //企业列表的跳转地址
                            );
                        }
                    }
                    //删除重复项
                    $collection = collect($arrInfo);
                    $arrInfo = $collection->unique('companyId');
                    return $arrInfo;
                }
            }
        }else{
            //获取58企业信息匹配不存在
            return 'error';
        }

//        if(preg_match_all("/<div class=\"main\">(.*)<div class=\"bottom\">/Uis", $listData, $arr)){
//            if(preg_match_all("/<dl(.*)<dd class=\"w271\">\s*<a href=(\'|\")(.*)(\'|\")(.*)<\/a>(.*)<\/dd>(.*)<\/dl>/Uis", $arr[1][0], $arr1)){
//                if(count($arr1[3]) > 0){
//                    $arrInfo = [];
//                    foreach($arr1[3] as $v){
//                        if(preg_match("/(.*)qy.58.com\/(.*)\/(\?(.*))?/Uis", $v, $arr2)){
//                            $arrInfo[] = array(
//                                'companyId' => trim($arr2[2]),//企业ID用户的唯一ID
//                                'companyUrl' => trim($v, '/') . '/'   //企业列表的跳转地址
//                            );
//                        }
//                    }
//                    //删除重复项
//                    $collection = collect($arrInfo);
//                    $arrInfo = $collection->unique('companyId');
//                    return $arrInfo;
//                }
//            }
//        }else{
//            //获取58企业信息匹配不存在
//            return 'error';
//        }
    }

    /**
     * 企业内容
     * @param $companyId
     * @param $companyUrl
     * @param $cookie
     * @return string
     */
    static public function companyCon($companyId, $companyUrl, $cookie){
        //$companyUrl = 'http://qy.58.com/44164476252174/';
        $con = getCurlCon($companyUrl, $cookie);
        if(preg_match_all("/<hr size=\"1\" noshade=\"noshade\">/Uis", $con, $arr)){
            //采集信息出错 可能该企业不存
            return 'err';
        }
        //使用phpQuery
        $con = \phpQuery::newDocument($con);
        //企业职位列表
        $jobListCon = pq(".wb-main .jobInfo")->find('.jobList')->html();//获取职位列表页数的职位数有没存在
        $jobArr = [];
        if(!empty($jobListCon)){
            $jobList = pq(".wb-main .jobInfo")->find('.jobList')->find('tbody tr');//有无职位列表
            foreach($jobList as $v){
                $job_title = trim(pq($v)->find('td')->find(".ml20 a")->html());//职位名称
                $jobArr[] = $job_title;
            }
        }
        //企业信息内容
        $companyName = trim(pq(".wb-main .compT")->find('.clearfix')->find('.businessName')->html());//公司名称
        if(empty($companyName)){
            return 'mq';//该企业为名企。直接跳过
        }
        $address = trim(pq(".wb-main .basicMsg")->find('.compony .fl')->find('var')->html());//公司地址
        //企业网址
        preg_match("/<li>\s*<span>企业网址：<\/span>\s*<a(.*)>(.*)<\/a>\s*<\/li>/Uis", $con, $arr2);
        $web = trim($arr2[2]);

        //随机一个职位信息
        $jobInfoUrl = pq(".wb-main .jobInfo")->find('.jobList')->find('tbody tr')->find('td')->find(".ml20 a")->attr('href');
        preg_match("/http:\/\/(.*).58.com(.*?)/Uis", $jobInfoUrl, $arr3);
        //获取手机站地址
        $mJobUrl = 'http://m.58.com/' . trim($arr3[1]) . trim($arr3[2]);
        $mCon = getCurlCon($mJobUrl, $cookie);
        $mCon = \phpQuery::newDocument($mCon);
        $number = trim(pq("#openCom")->find('.phoneWrap')->find("a")->attr('phoneno'));//手机号码
        if(!empty($number) && strlen($number) == '11'){
            $mobile = $number;
            $phone = '';
        }else{
            $mobile = '';
            $phone = $number;
        }
        $contacts = trim(pq("#openCom")->find('.contact')->find("span")->next()->html());//联系人
        $email = '';
        //循环职位列表分页
        for($i = 2; $i < 100; $i++){
            $jobUrl = trim($companyUrl, '/') . '/574/pn' . $i . '/';//职位列表url地址
            $jobCon = getCurlCon($jobUrl);
            $jobCon = \phpQuery::newDocument($jobCon);
            $jobListCon = pq(".wb-main .jobInfo")->find('.jobList')->html();//获取职位列表页数的职位数有没存在
            if(!empty($jobListCon)){
                $jobList = pq(".wb-main .jobInfo")->find('.jobList')->find('tbody tr');//公司名称
                if(!empty($jobList)){
                    foreach($jobList as $v){
                        $job_title = trim(pq($v)->find('td')->find(".ml20 a")->html());//职位名称
                        $jobArr[] = $job_title;
                    }
                }
            }else{
                break;//退出循环
            }
        }
        $jobArr = array_unique($jobArr);//合并相同的职位名称
        $remarks = implode('，', $jobArr);//链接职位名称
        //企业基本信息
        $basicArr = array(
            'name' => $companyName,
            'address' => $address,
            'web' => $web,
            'contacts' => $contacts,
            'phone' => $phone,
            'mobile' => $mobile,
            'email' => $email,
            'remarks' => $remarks,
            'created_at' => date('Y-m-d H:i:s', time()),
            'updated_at' => date('Y-m-d H:i:s', time()),
            'visit_time' => date('Y-m-d H:i:s', time())
        );

        //简历内容
        $arrayCon = array(
            'companyId' => $companyId,
            'companyUrl' => $companyUrl,
            'companyArr' => $basicArr,
        );
        return $arrayCon;
    }
}
